<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/27.
 */

namespace App\Http\Controllers\Traits;

trait ValidateTrait
{
    /**
     * 校验规则，
     * 支持在控制器中定义函数，
     * 验证规则  public function rules (): array {return []}.
     * 提示信息  public function message (): array {return []}.
     * 自定义参数转换  public function attributes (): array {return []}.
     * 或在Request/System中定义类.命名规则为 modelRequest,
     *  如：数据表名称，systems, 则模型名称为 System
     *  请求验证类名称为 SystemRequest
     * 如果在插件中 则可以取消 System 命名空间.
     */
    protected function validated(): void
    {
        $obj = [$this, $this->getValidated()];
        $data = ['rules' => [], 'message' => [], 'attributes' => []];
        foreach ($obj as $item) {
            if (!$item) {
                continue;
            }
            foreach ($data as $key => $val) {
                if (method_exists($item, $key) && 0 === \count($val)) {
                    $data[$key] = $item->{$key}();

                    continue;
                }
                if (property_exists($item, $key)) {
                    $data[$key] = $item->{$key};
                }
            }
        }

        request()->validate($data['rules'], $data['message'], $data['attributes']);
    }

    private function getValidated()
    {
        $folder = 'Http'.\DIRECTORY_SEPARATOR.'Request'.\DIRECTORY_SEPARATOR.'System';
        // 当在插件中执行时不需要 System

        if ($this->getAddonName()) {
            $folder = 'Request';
        }
        $request = $this->getNamespaceName($this->getModelName().'Request', $folder);

        return $request ? new $request() : null;
    }
}
